package com.guiwu.gteway.industryapp.Device.module;

import com.guiwu.gteway.industryapp.Frame.FrameHelper;

/**
 * Created by qiaoguan on 2018/3/24. local类型的监控点
 */

public class LocalMonitor extends Monitor {
    private final static String R = "R";
    private final static String S = "S";
    private final static String A = "A";
    private static final String TAG = "MonitorControl";

    public LocalMonitor(MonitorData monitorData) {
        super(monitorData);
    }

    public int getMonitorType(){
        if (dataType.equalsIgnoreCase("bit")){
            return BIT;
        }else if (dataType.equalsIgnoreCase("bit16"))
            return BIT16;
        else return BIT32;
    }

    @Override
    public String getValue() {
        return addDeciaml(value,decimal[1]) + " " + unit;
    }

    @Override
    public String getTypeValue(int inputValue) {
        return  addDeciaml(inputValue,decimal[1]) + " " + unit;
    }

    @Override
    public void sendCmd(String deviceId ,String apiKey,boolean coil){
        String cmdFrame;
        if ((cmdFrame = getCoilFrame(coil)) == null)
            return;
        handleCmd(deviceId,apiKey,cmdFrame);
    }

    @Override
    public void sendCmd(String deviceId, String apiKey, int value) {
        String cmdFrame;
        if ((cmdFrame = getRegFrame(value)) == null)
            return;
        handleCmd(deviceId,apiKey,cmdFrame);
    }

    @Override
    public String getCoilFrame(boolean coil){
        int address = 0;
        String cmd = null;
        if (coil == getSwitchState())
            return null;

        switch (addressType.toUpperCase()) {
            case R:
                address = 4096 + addressAdd;
                break;
            case S:
                address = 4352 + addressAdd;
                break;
        }

        if (protocol.equalsIgnoreCase("RTU")) {
            cmd = FrameHelper.writeCoilRTU(slaveAdr, address, coil);
        }else if (protocol.equalsIgnoreCase("ASCII")){
            cmd = FrameHelper.writeCoilASSIC(slaveAdr, address, coil);
        }
        return cmd;
    }

    @Override
    public String getRegFrame(int value){
        int address;
        String cmd = null;
        if (protocol.equalsIgnoreCase("RTU")){
            if (addressType.toUpperCase().equals(A)){
                address = 5120 + addressAdd;
                cmd = FrameHelper.wrightRegisterRTU(slaveAdr,address,value);
            }
        }else if (protocol.equalsIgnoreCase("ASCII")){
            if (addressType.toUpperCase().equals(A)){
                address = 5120 + addressAdd;
                cmd = FrameHelper.writeRegistASSIC(slaveAdr,address, value);
            }
        }

        return cmd;
    }


    @Override
    public String toString() {
        return "类型：local    " + super.toString();
    }


}
